﻿#region Copyright
// Copyright (c) 2011-2012 RaisingForce Team (Alikin Sergey)
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics.Contracts;
using System.IO;
using System.Reflection;
using System.Security;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using RaisingForce.Raise.Presentation.Localization;
using RaisingForce.Raise.Presentation.Names;
using RaisingForce.RaiseHardwareTest.Configuration;
using RaisingForce.RaiseHardwareTest.Hardware;

namespace RaisingForce.RaiseHardwareTest
{
    internal static class ApplicationHelper
    {
        #region Static Constructor

        static ApplicationHelper()
        {
            icon = getEmbeddedImage(iconPath);
            productImage = getEmbeddedImage(productImagePath);
            companyImage = getEmbeddedImage(companyImagePath);
        }

        #endregion

        #region Number Formatting Constants

        /// <summary>
        /// Gets maximum number of digits after point
        /// in string representation of distance values.
        /// </summary>
        public const int DistanceValueMaxDigits = 2;

        public static double GetRoundedDistanceValue(double value, int maxDigits)
        {
            Contract.Requires(maxDigits >= 0);
            return Math.Round(value, maxDigits);
        }

        #endregion

        #region Configuration Constants

        public const string CustomSettingsConfigurationSection =
            "customSettings";

        public const string DefaultHardwareSettingsPath = "HardwareSettings.xml";

        public const string DefaultHardwarePluginsMask = "Raise.Hardware.*.dll";

        #endregion

        #region Hardware Configuration Declarations

        private static readonly Lazy<HardwareConfiguration> _hardwareConfiguration =
            new Lazy<HardwareConfiguration>(
                () => ((CustomSettingsSection)ConfigurationManager
                        .GetSection(CustomSettingsConfigurationSection))
                        .Hardware
                        .CreateHardwareConfiguration(),
                isThreadSafe: true);

        public static HardwareConfiguration HardwareConfiguration
        {
            get
            {
                Contract.Ensures(Contract.Result<HardwareConfiguration>() != null);
                return _hardwareConfiguration.Value;
            }
        }

        #endregion

        #region RegisterSupportedLanguages Static Method

        public static void RegisterSupportedLanguages()
        {
            var section = (CustomSettingsSection)ConfigurationManager
                .GetSection(CustomSettingsConfigurationSection);
            if (section != null
                && section.SupportedLanguages != null
                && section.SupportedLanguages.Count > 0)
            {
                SupportedLocalizationLanguages.Instance.AddMultipleLanguages(
                    section.SupportedLanguages.GetLocalizationLanguages());
            }
            else
            {
                if (SupportedLocalizationLanguages.Instance.Count == 0)
                {
                    SupportedLocalizationLanguages.Instance.AddLanguage(
                        LocalizationLanguage.CreateInvariant());
                }
            }
        }

        #endregion

        #region Private getImage Methods

        private static ImageSource getEmbeddedImage(string imagePath)
        {
            Contract.Ensures(Contract.Result<ImageSource>() != null);
            return new BitmapImage(
                new Uri("pack://application:,,,/;component/" + imagePath));
            //Stream imageStream = Application.GetResourceStream(
            //    new Uri("pack://application:,,,/;component/" + imagePath))
            //    .Stream;
            //BitmapImage image = new BitmapImage
            //{
            //    CacheOption = BitmapCacheOption.OnDemand
            //};
            //image.BeginInit();
            //image.StreamSource = imageStream;
            //image.EndInit();
            //return image;
        }

        private static ImageSource getExternalImage(string imagePath)
        {
            return new BitmapImage(
                new Uri(imagePath));
        }

        private static ImageSource getFileImage(string imagePath)
        {
            return new BitmapImage(
                new Uri(Path.GetFullPath(imagePath)));
        }

        private static ImageSource getIcon(
            string imagePath,
            params Func<string, ImageSource>[] getImageSourceActions)
        {
            Contract.Requires(imagePath != null);
            Contract.Requires(getImageSourceActions != null);
            string usingImagePath = imagePath.Trim();
            foreach (var action in getImageSourceActions)
            {
                try
                {
                    return action(usingImagePath);
                }
                catch (UriFormatException) { }      // Uri constructor
                catch (IOException) { }             // Path.GetFullPath or I/O stream error
                catch (ArgumentException) { }       // Path.GetFullPath
                catch (NotSupportedException) { }   // Path.GetFullPath
                catch (SecurityException) { }       // Path.GetFullPath
            }
            return null;
        }

        #endregion

        #region Icon Static Property

        private static readonly ImageSource icon;

        private const string iconPath = "Images/AppIcon.ico";

        public static ImageSource Icon
        {
            get
            {
                Contract.Ensures(Contract.Result<ImageSource>() != null);
                return icon;
            }
        }

        #endregion

        #region ProductImage Static Property

        private static readonly ImageSource productImage;

        private const string productImagePath = "Images/Raise.png";

        public static ImageSource ProductImage
        {
            get
            {
                Contract.Ensures(Contract.Result<ImageSource>() != null);
                return productImage;
            }
        }

        #endregion

        #region CompanyImage Static Property

        private static readonly ImageSource companyImage;

        private const string companyImagePath = "Images/RaisingForce.png";

        public static ImageSource CompanyImage
        {
            get
            {
                Contract.Ensures(Contract.Result<ImageSource>() != null);
                return companyImage;
            }
        }

        #endregion

        #region PluginsInfo Static Property

        public static IEnumerable<HardwarePluginInfo> PluginsInfo
        {
            get
            {
                Contract.Ensures(Contract.Result<IEnumerable<HardwarePluginInfo>>() != null);
                return HardwarePluginInfoCollection.Instance;
            }
        }

        #endregion

        #region GetFlagIcon Static Method

        private static readonly IDictionary<string, ImageSource> _flags =
            new Dictionary<string, ImageSource>();

        public static ImageSource GetFlagIcon(
            string cultureName,
            string imagePath = null)
        {
            Contract.Requires(cultureName != null);
            lock (_flags)
            {
                if (_flags.ContainsKey(cultureName))
                {
                    return _flags[cultureName];
                }
                if (string.IsNullOrWhiteSpace(imagePath))
                {
                    return null;
                }
                ImageSource icon = getIcon(imagePath,
                    getEmbeddedImage,
                    getExternalImage,
                    getFileImage);
                if (icon != null)
                {
                    _flags.Add(cultureName, icon);
                }
                return icon;
            }
        }

        #endregion
    }
}
